# _*_ coding:utf-8 _*_
# @Time  : 2022.07.08
# @Author: zizlee

""" 接口废弃 文件待删除 """
import datetime
from fastapi import APIRouter, Header, Body, Query
from pydantic import BaseModel, datetime_parse
from hutool import security, utils
from db import FAConnection
from v1_all_api.all_response import AllResponse
from v1_all_api.all_utils import data_utils

role_api = APIRouter()


# @role_api.get('/roles/')  # 查询系统角色
async def get_role():
    db_conn = FAConnection()
    records = db_conn.query("SELECT id,role_name,role_code FROM ruizy_role;")
    return AllResponse.operate_successfully(data=records)


class RoleMenuItem(BaseModel):
    role_code: int
    menu_code: int
    expire: datetime_parse.date


# @role_api.post('/roleMenu/')  # 设置角色下的菜单权限
async def create_role_menu(ruizy_token: str = Header(...), auth: RoleMenuItem = Body(...)):
    person = security.decrypt_access_token(ruizy_token)
    if not person:
        return AllResponse.no_authorization()
    if not security.operator_is_super_admin(person):
        return AllResponse.forbidden_error()
    db_conn = FAConnection()
    # 查询是否存在
    exist_sql = "SELECT id FROM ruizy_role_menu WHERE role_code=%s AND menu_code=%s LIMIT 1;"
    exist_obj = db_conn.query(exist_sql, param=[auth.role_code, auth.menu_code], keep_conn=True, fetchone=True)[0]
    if exist_obj:
        sql = "UPDATE ruizy_role_menu SET expire=%s WHERE id=%s;"
        prm = (auth.expire.strftime('%Y-%m-%d'), exist_obj['id'])
    else:
        sql = "INSERT INTO ruizy_role_menu (role_code,menu_code,expire) VALUES (%s,%s,%s);"
        prm = (auth.role_code, auth.menu_code, auth.expire.strftime('%Y-%m-%d'))
    _, success = db_conn.execute(sql, param=prm)
    return AllResponse.operate_successfully() if success else AllResponse.server_error()


@role_api.get('/roleMenus/')  # 查询角色下的菜单权限
async def get_role_menu(ruizy_token: str = Header(...), r: int = Query(..., ge=1)):

    def handle_menu_auth(m):
        m['noEdit'] = False
        m['access'] = m['expire'] and m['expire'] >= today
        m['expire'] = m['expire'].strftime('%Y-%m-%d') if m['expire'] else None
        m['hidden_zh'] = '是' if m['hidden'] else '否'
        return m

    person = security.decrypt_access_token(ruizy_token)
    if not person:
        return AllResponse.no_authorization()

    role_code = r
    today = datetime.date.today()
    sql = """
        SELECT a.id,a.menu_name,a.menu_code,a.parent_code,a.hidden,b.expire 
        FROM ruizy_menu As a LEFT JOIN ruizy_role_menu As b ON a.menu_code=b.menu_code AND b.role_code=%s 
        ORDER BY a.sorted,a.id;
    """
    db_conn = FAConnection()
    records = db_conn.query(sql, param=[role_code])
    records = list(map(handle_menu_auth, records))
    role_menu = data_utils.list2tree(records, pkey='parent_code', ckey='menu_code', fvalue='0')
    return AllResponse.operate_successfully(data=role_menu)

""" 接口废弃 文件待删除 """
